// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package ripple

import (
	"sync"
)

// ▒▒
type RefCounter struct {
	zero func()
	sync.Mutex
	numref int
}

func NewRefCounter(zero func()) *RefCounter {
	return &RefCounter{
		zero: zero,
	}
}

func (rc *RefCounter) Reset(zero func()) {
	rc.zero = zero
}

func (rc *RefCounter) Hold() {
	rc.add(1)
}

func (rc *RefCounter) Clunk() {
	rc.add(-1)
}

func (rc *RefCounter) add(change int) {
	var trigger bool
	defer func() {
		if trigger {
			rc.zero()
		}
	}()
	rc.Lock()
	defer rc.Unlock()
	rc.numref += change
	if rc.numref < 0 {
		panic("#")
	}
	if rc.numref > 0 {
		return
	}
	trigger = true
}
